<template>
  <div
    v-loading="loading"
    element-loading-customClass="ne-loading"
    element-loading-background="rgba(255, 255, 255, 0.6)"
  >
    <DicTable
      ref="dictable"
      stripe
      border="full"
      align="center"
      :columnData="tableColumns"
      :tableData="tableData"
      :loading="tableLoading"
      :currentPage="parseInt(tablePage.pageIndex)"
      :pageSize="parseInt(tablePage.pageSize)"
      :totalResult="parseInt(tablePage.rowCount)"
      :pager="true"
      @on-page-change="handlePageChange"
      width="100%"
    >
      <template #opt="{ row }">
        <el-popover placement="top" width="200">
          <div style="text-align: center; margin: 0">
            <el-button size="mini" @click="accepTance(row, 50030003, 13241001)"
              >订 单</el-button
            >
            <el-button size="mini" @click="accepTance(row, 50030002, 13241001)"
              >需求单</el-button
            >
          </div>
          <el-button slot="reference">受理</el-button>
        </el-popover>
        <el-button @click="retreat(row)">退回</el-button>
      </template>
      <template #extCustId="{ row }">
         <span v-if="row.extCustId=='-1' || row.extCustId == 'null'"></span>
        <span v-else>{{row.extCustId}}</span>
      </template>
    </DicTable>
    <!-- 退回弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      title="商机任务回退"
      :before-close="dialogClose"
      :visible.sync="listDialog"
      width="700px"
    >
      <div class="prolist-container">
        <div class="retreatContent">
          <el-input
            type="textarea"
            :rows="4"
            clearable
            v-model="retreaInput"
            placeholder="请输入回退原因"
          ></el-input>
        </div>
        <div class="primaryButton">
          <el-button type="primary" @click="affirmClick">确认</el-button>
          <el-button type="primary" @click="retreatClick">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <province-custpicker
      @updateshow="custPickerShowHandler"
      @pickerEnd="pickerEnd"
      @prohsChange="prohsChange"
      :show="orderPreTaskVisible"
      :Data="provinceCustList"
    >
    </province-custpicker>
    <el-dialog
      custom-class="ne-sc-dialog"
      title="当前集团客户未查询到省内客户，将自动同步客户至以下区域"
      v-if="provdVisible"
      :visible.sync="provdVisible"
      width="25%"
    >
      <el-form
        :inline="false"
        :model="provdForm"
        class="ne-prov-form"
        label-width=".7rem"
      >
        <el-form-item label="省：">
          <el-select
            v-model="provdForm.province"
            placeholder="请选择"
            :disabled="provdForm.provinceOpt.length <= 1"
          >
            <el-option
              v-for="(item, index) in provdForm.provinceOpt"
              :key="index"
              :label="item.regionName"
              :value="item.regionId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市：">
          <el-select
            v-model="provdForm.city"
            placeholder="请选择"
            filterable
            :disabled="provdForm.cityOpt.length <= 1"
          >
            <el-option
              v-for="(item, index) in provdForm.cityOpt"
              :key="index"
              :label="item.regionName"
              :value="item.regionId"
            ></el-option>
          </el-select>
        </el-form-item>
        <div class="text-center">
          <el-button type="primary" @click="prodOnSubmit">提交</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import DicTable from "@/components/public/DicTable";
import OrderService from "@/api/order/OrderService.js";
import { mapState, mapGetters } from "vuex";
import ElInput from "../../../node_modules/element-ui/packages/input/src/input.vue";
import ProvinceCustpicker from "@/components/order/ProvinceCustpicker";
export default {
  components: {
    ElInput,
    DicTable,
    ProvinceCustpicker,
  },
  computed: {
    ...mapState("user", ["user"]),
    ...mapGetters(["orderPosInfochange"]),
  },
  data() {
    return {
      loading: false,
      rows: {},
      provdForm: {
        province: "",
        city: "",
        provinceOpt: [],
        cityOpt: [],
      },
      provdVisible: false,
      provinceCustList: {},
      orderPreTaskVisible: false,
      tablePage: {
        pageCount: "",
        pageIndex: 1,
        pageSize: 10,
        rowCount: 0,
      },
      pageInfo: {
        pageCount: "",
        orgId: "",
        pageIndex: 1,
        pageSize: 10,
      },
      tableLoading: true,
      tableData: [],
      tableColumns: [
        {
          field: "applyCode",
          title: "任务单编号",
          showOverflow: true,
          width: 200,
        },
        { slotName: "opt", title: "操作", width: 200 },
        {
          field: "custName",
          title: "客户名称",
          showOverflow: true,
          width: 300,
        },
        {
          slotName: "extCustId",
          title: "省客户ID",
          showOverflow: true,
          width: 300,
        },
        { field: "saleCd", title: "商机ID", showOverflow: true, width: 200 },
        {
          field: "saleName",
          title: "商机名称",
          showOverflow: true,
          width: 200,
        },
        {
          field: "prodOfferName",
          title: "销售品名称",
          showOverflow: true,
          width: 200,
        },
        {
          field: "reqType",
          title: "需求单类型",
          showOverflow: true,
          width: 200,
        },
        {
          field: "serviceOfferName",
          title: "业务类型",
          showOverflow: true,
          width: 150,
        },
        {
          field: "orderDate",
          title: "要求完成日期",
          showOverflow: true,
          width: 200,
        },
        {
          field: "contractCd",
          title: "合同编码",
          showOverflow: true,
          width: 200,
        },
        {
          field: "staffName",
          title: "商机发起人",
          showOverflow: true,
          width: 150,
        },
      ],
      listDialog: false,
      retreaInput: "",
      rwsList: {},
    };
  },
  mounted() {
    this.pageInfo.orgId = this.user.orgId;
    this.getopportunityTask();
  },
  methods: {
    /**
     * 父级更改控制dialog的显示隐藏
     */
    custPickerShowHandler(val) {
      this.orderPreTaskVisible = val;
    },
    /**
     * 监听省客户选择完成
     */
    async pickerEnd(item) {
      this.loading = true;

      let param = {
        actType: "ADD",
        custId: this.rows.custId,
        provinceCustId: item.custId,
        jtCustNumber: this.rows.custNumber,
        provinceCustNumber: item.custNumber,
        provinceCustName: item.custName,
        provinceId: item.commonRegionId,
        lanId: item.commonRegionId,
        staffId: this.user.staffId,
        statusCd: "1000",
      };
      let result = await OrderService.insertProvinceCustRel(param);
      if (result.meta.resultCode == "0") {
        this.loading = false;
        this.$store.commit("orders/SET_RESP_CUSTID", item.custId);
        this.goOrderAddPage();
      } else {
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: "error",
        });
      }
      console.log(
        "pickerEnd获取到：",
        item,
        "参数格式：",
        param,
        "返回结果",
        result
      );
    },
    async prohsChange(arg) {
      const ctResult = await this.loadCustList(arg);
      if (~~ctResult.code == 200) {
        if (ctResult.meta.customer.length > 0) {
          this.provinceCustList = ctResult.meta;
        }
      }
    },
    async getopportunityTask() {
      const result = await OrderService.ReqTaskList(this.pageInfo);
      if (result.code == 200 && result.meta.orderOppoLists.length >= 1) {
        this.tablePage.pageIndex = result.meta.pageInfo.pageIndex;
        this.tablePage.pageSize = result.meta.pageInfo.pageSize;
        this.tablePage.rowCount = result.meta.pageInfo.rowCount;
        this.tableData = result.meta.orderOppoLists;
        this.tableLoading = false;
      } else {
        this.tableLoading = false;
      }
    },
    /**
     * 跳转到新建项目页面
     */
    goOrderAddPage() {
      if (this.rows.custId) {
        // 新建订单、信息录入需要清缓存刷新数据
        this.$router.options.routes.map((item) => {
          if (item.name == "orderadd" || item.name == "inforentryppm") {
            item.meta.isFefresh = true;
          }
        });
        this.$store.commit("orders/SET_STEPACTIVE", 2);
        this.$store.commit("orders/SET_ELE_LABEL", this.rows.type);
        this.$router.push({ name: "orderadd", query: { taskList: this.rows } });
      } else {
        // 没选择客户时提示
        this.$confirm("请先选择客户！", "提示", {
          confirmButtonText: "知道了",
          type: "warning",
          showCancelButton: false,
          center: true,
        }).then((done) => {
          done();
        });
      }
    },

    /**
     * 加载省客户关系
     */
    async loadCustList(pageInfo) {
      let condition = {
        qryType: "INTERFACE",
        PageFlag: "1", //固定
        custName: this.rows.custName, //客户名称
        provRegionCode: this.user.regionCode,
        commonRegionId: this.user.regionId,
        listShowFlag: "orderShow", //固定
        ...pageInfo,
      };
      const custData = await OrderService.provinceCustList(condition);
      return custData;
    },
    async prodOnSubmit() {
      let regionId = "";
      if (this.provdForm.city !== "") {
        regionId = this.provdForm.city;
      } else {
        regionId = this.provdForm.province;
      }

      OrderService.syncProvinceCust({
        custId: this.rows.custId,
        lanId: this.rows.regionId,
        regionId: regionId + "",
      });
      this.goOrderAddPage();
    },

    /**
     * 打开省市选择
     */
    async openAutoAsyncPrompt() {
      this.provdVisible = true;
      const result = await OrderService.getRegionCodeList({
        regionId: this.user.regionId,
        regionType: this.user.regionType,
      });
      this.loading = false;
      if (result.meta) {
        this.provdForm.provinceOpt = result.meta.proArr;
        this.provdForm.cityOpt = result.meta.lenArr;
        this.provdForm.province = this.provdForm.provinceOpt[0].regionId;
        if (this.provdForm.cityOpt.length == 1) {
          this.provdForm.city = this.provdForm.cityOpt[0].regionId;
        }
      } else {
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: "error",
        });
      }
    },
    /**
     * 受理事件
     */
    async accepTance(row, id, type) {
      this.loading = true;
      row.orderstage = id;
      row.type = type;
      this.rows = row;
      // this.$router.push({ name: "orderadd", query: { taskList: this.rows } });
      // 判断是否是省客户:接口名:getTestProvCount
      if (
        row.extCustId == "-1" ||
        row.extCustId == "" ||
        row.extCustId == "null"
      ) {
        //当商机列表省ID为空时，走先查后创
        let pilotResult = await OrderService.isPilotProvince({
          regionId: this.user.regionId,
          regionCode: this.user.regionCode,
          regionType: this.user.regionType,
        });
        let isPilot = pilotResult.meta.count;
        if (isPilot == "0") {
          //非试点省:直接跳转到新建项目页面;
          this.loading = false;
          this.goOrderAddPage();
        } else {
          //加载省客户关系
          let pageInfo = {
            pageIndex: 1,
            pageSize: 10,
          };
          const ctResult = await this.loadCustList(pageInfo);
          if (ctResult.code == "200") {
            this.loading = false;
            if (ctResult.meta.customer && ctResult.meta.customer.length > 0) {
              this.provinceCustList = ctResult.meta;
              this.orderPreTaskVisible = true;
            } else {
              this.openAutoAsyncPrompt();
            }
          }
        }
      } else {
        this.$store.commit("orders/SET_STEPACTIVE", 2);
        this.$store.commit("orders/SET_ELE_LABEL", this.rows.type);
        this.$store.commit("orders/SET_RESP_CUSTID", row.extCustId);
        this.$router.push({ name: "orderadd", query: { taskList: this.rows } });
      }

      //row.elecLabel = type ;
    },
    /**
     * 退回事件
     */
    retreat(row) {
      this.rwsList = row;
      this.listDialog = true;
    },
    /**
     * 分页事件
     */
    handlePageChange({ currentPage, pageSize }) {
      this.pageInfo.pageIndex = currentPage;
      this.pageInfo.pageSize = pageSize;
      this.getopportunityTask();
    },
    /**
     * 回退弹窗关闭事件
     */
    dialogClose() {
      this.listDialog = false;
      this.retreaInput = "";
      this.rwsList = {};
    },
    /**
     * 弹窗中-确认回退事件
     */
    affirmClick() {
      if (this.retreaInput === "") {
        this.$message({
          message: "请填写【回退原因】",
          type: "warning",
          showClose: true,
        });
      } else if (this.retreaInput !== "") {
        let params = {
          CUST_ID: this.rwsList.custId,
          APPLY_CODE: this.rwsList.applyCode,
          STAFF_ID: this.user.staffId || "",
          BACK_REASON: this.retreaInput,
        };
        this.returnTaskClick(params);
      }
    },
    async returnTaskClick(params) {
      const result = await OrderService.returnBusinessTask(params);
      if (result.code == 200) {
        //if(result.meta.Msg instanceof Object){}
        this.$message({
          message: result.meta.Msg.message,
          type: "success",
          showClose: true,
        });
        this.dialogClose();
      } else {
        //if(result.meta.Msg instanceof Object){ }
        this.$message({
          message: result.meta.Msg.message,
          type: "warning",
          showClose: true,
        });
      }
    },
    /**
     * 弹窗中-返回事件
     */
    retreatClick() {
      this.dialogClose();
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .ne-sc-dialog .el-dialog__header .el-dialog__title {
  font-size: $fontSize_v2 !important;
}
.el-dialog__body {
  padding: 10px 20px;
}
.primaryButton {
  text-align: center;
  margin-top: 10px;
  .el-button--primary {
    width: 100px;
  }
}
</style>
